/*
Source : https://leetcode.com/problems/partition-list/
Author : nflush@outlook.com
Date   : 2016-07-05
*/

/*
Total Accepted: 70183 Total Submissions: 233408 Difficulty: Medium

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Subscribe to see which companies asked this question
Have you met this question in a real interview?
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode ll = ListNode(0);
        ListNode *pre = &ll;
        ListNode *ph = head;
        ll.next = head;
        ListNode *pm;
        ListNode *pr;

        // find the first right node
        for(;ph && ph->val < x; ph=ph->next, pre=pre->next);
        if (ph){
            pm = ph;
            pr = pm;
            ph = ph->next;
        } else {
            return head;
        }
        for (;ph;ph=ph->next){
            if (ph->val < x){
                pre->next = ph;
                pre = ph;
                pm->next = NULL;
            } else{
                pm->next = ph;
                pm = ph;
            }
        }
        pre->next = pr;
        return ll.next;
    }
};
